<?php

namespace app\user\controller;

use app\model\ItemType as ModelItemType;
use app\model\DoorTime as ModelDoorTime;
use app\user\logic\Order as UserLogicOrder;
use app\model\UserOrder as ModelUserOrder;
use app\model\Package as ModelPackage;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\UserOrderLog as ModelUserOrderLog;
use app\model\CourierInfo as ModelCourierInfo;


/**
 * 订单相关类
 * Class Common
 * @package app\user\controller
 */
class Order extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 取消订单 \n
     * URI : /order.cancel
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  orderId       | int    | 必填  | 订单id
     *  message       | string | 必填  | 取消原因
     *
     * @return
     *  name        |  type  | description
     * -------------|--------|-------------
     *  ----------- | ------ | 无
     */
    public function cancelOrder()
    {
        $int_order_id = intval($this->_getContentParams('orderId'));
        $bool_res = ModelUserOrder::getInstance()->checkOrderId($int_order_id);
        _toCompare($bool_res, '==', false, 14012);

        $str_message = strval($this->_getContentParams('message'));
        _toCompare(in_array($str_message, ['不小心点错了', '不想寄件了', '寄件信息填错了']), '==', false, 14013);

        $res = UserLogicOrder::getInstance()->cancelOrder($int_order_id, $str_message);
        $logRes = ModelUserOrderLog::getInstance()->addOrderLog($int_order_id,4,$this->user_id,$str_message);//写入订单记录

        if ($res && $logRes){
            //修改快递员订单表订单状态------快递员已接单
            $courierOrder = ModelCourierOrder::getInstance()->toFind(['order_id'=>$int_order_id],'id');
            if ($courierOrder){
                $up_res = ModelCourierOrder::getInstance()->toUpdate(['id'=>$courierOrder['id']],['state'=>0]);
                if ($up_res){
                    _returnData();
                }else{
                    _returnError(10011);
                }
            }else{
                _returnData();
            }

        }
        _returnError(10011);
    }

    /**
     * 订单详情 \n
     * URI : /order.info
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  orderId       | int    | 必填  | 订单id
     *
     * @return
     *  name              |  type  | description
     * -------------------|--------|-------------
     *  info              | array  | 详情
     *
     * info
     *  name              |  type  | description
     * -------------------|--------|-------------
     *  senderName        | string | 寄件人姓名
     *  senderPhone       | string | 寄件人电话
     *  senderAddress     | string | 寄件人地址
     *  senderCityName    | string | 寄件人城市
     *  recipientCityName | string | 收件人城市
     *  recipientName     | string | 收件人姓名
     *  recipientPhone    | string | 收件人电话
     *  recipientAddress  | string | 收件人地址
     *  orderState        | string | 订单状态
     *  expressState      | string | 物流状态
     *  itemType          | string | 物品类型
     *  itemWeight        | string | 物品重量
     *  itemPrice         | string | 物品价值
     *  orderAmount       | string | 订单金额
     *  pickupCode        | string | 取件码
     *  orderSn           | string | 订单号
     *  addTime           | string | 下单时间
     *  recipientTime     | string | 收件时间
     */
    public function orderInfo()
    {
        $order_id = $this->_getContentParams('orderId');
        $bool_res = ModelUserOrder::getInstance()->checkOrderId($order_id);
        _toCompare($bool_res, '==', false, 14012);

        $field = 'recipient_info,sender_info,order_state as orderState,item_type as itemType,item_weight as itemWeight,item_price as itemPrice,order_amount as orderAmount,pick_code as pickupCode,order_sn as orderSn,gmt_create as addTime,recipient_time as recipientTime,door_time as doorTime,first_heavy_fee as firstFee,other_heavy_fee as otherFee,protect_price as protectPrice,express_name as expressName,express_order_sn as expressSn,clear_reason as clearReason,recipient_time as recipientTime,gmt_modified as clearTime';
        $info = ModelUserOrder::getInstance()->toFind(['order_id' => $order_id], $field);

        //寄件人
        $sender_info = json_decode($info['sender_info'], true);
        $info['senderName'] = $sender_info['name'];
        $info['senderPhone'] = $sender_info['phone'];
        $info['senderAddress'] = $sender_info['provName'] . $sender_info['cityName'] . $sender_info['countyName'] . $sender_info['streetName'] . $sender_info['address'];
        $info['senderCityName'] = $sender_info['cityName'];

        //收件人
        $recipient_info = json_decode($info['recipient_info'], true);
        $info['recipientName'] = strval($recipient_info['name']);
        $info['recipientPhone'] = strval($recipient_info['phone']);
        $info['recipientAddress'] = strval($recipient_info['provName']) . strval($recipient_info['cityName']) . strval($recipient_info['countyName']) . strval($recipient_info['streetName']) . strval($recipient_info['address']);
        $info['recipientCityName'] = strval($recipient_info['cityName']);

        //接单快递员信息
        $courierId = ModelCourierOrder::getInstance()->toValue(['order_id'=>$order_id,'is_pick'=>1],'courier_id as courierId');
        $courierInfo = ModelCourierInfo::getInstance()->toFind(['id'=>$courierId],'real_name as realName,mobile,type');
        $info['courierName'] = $courierInfo['realName'];
        $info['courierMobile'] = $courierInfo['mobile'];
        $info['courierType'] = $courierInfo['type'];

        _returnData(['info' => $info]);
    }

    /**
     * 订单删除 \n
     * URI : /order.del
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  orderId       | int    | 必填  | 订单id
     *
     * @return
     *  name        |  type  | description
     * -------------|--------|-------------
     *  ----------- | ------ | 无
     */
    public function delOrder()
    {
        $order_id = $this->_getContentParams('orderId');
        _toValidate('id',$order_id,10009);
        $order_info = ModelUserOrder::getInstance()->toFind(['order_id' => $order_id], 'order_id,order_state');
        _toCompare(isset($order_info['order_id']), '==', false, 14012);

        $res = ModelUserOrder::getInstance()->toUpdate(['order_id' => $order_id], ['is_delete' => 1]);
        if ($res) _returnData();
        _returnError(10012);
    }

    /**
     * 订单列表 \n
     * URI : /order.list
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *
     * @return
     *  name        |  type  | description
     * -------------|--------|-------------
     *  completedList  | array | 已完成列表
     *  noCompletedList| array  | 未完成列表
     *
     * completedList(noCompletedList)
     *  name        |  type  | description
     * -------------|--------|-------------
     *  orderId     | int    | 订单id
     *  name        | string | 姓名
     *  phone       | string | 手机号
     *  address     | string | 收件人地址
     *
     */
    public function orderList()
    {
        $completedList = $this->getOrderList('completed');

        $noCompletedList = $this->getOrderList('noCompleted');

        _returnData(['completedList' => $completedList, 'noCompletedList' => $noCompletedList]);
    }


    public function getOrderList($order_type)
    {
        //查询条件
        $where = UserLogicOrder::getInstance()->getOrderListWhere($order_type);
        $where['user_id'] = $this->user_id;
        $where['is_delete'] = 0;

        $arr_list = ModelUserOrder::getInstance()->toSelect(
            $where,
            'order_id as orderId,recipient_info,order_state as orderState'
        );

        foreach ($arr_list as &$value) {
            $recipient_info = json_decode($value['recipient_info'], true);
            $value['name'] = isset($recipient_info['name']) ? (string)$recipient_info['name'] : '';
            $value['phone'] = isset($recipient_info['phone']) ? (string)$recipient_info['phone'] : '';
            $value['address'] = isset($recipient_info['provName']) ? (string)($recipient_info['provName'] . $recipient_info['cityName'] . $recipient_info['countyName'] . $recipient_info['streetName'] . $recipient_info['address']) : '';
            unset($value['recipient_info']);
        }
        unset($value);

        return $arr_list;
    }

    /**
     * 添加订单 \n
     * URI : /order.add
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *  senderInfo    | json   | 必填  | 寄件人信息
     *  recipientInfo | json   | 必填  | 收件人信息
     *  doorType      | string | 必填  | 上门时间类型（rightNow：二小时上门, today：今天, tomorrow：明天, afterTomorrow：后天）
     *  doorTime      | string | 必填  | 上门时间 (19:00-21:00)
     *  weight        | string | 必填  | 重量
     *  itemTypeId    | string | 必填  | 物品类型id
     *  itemPrice     | string | 必填  | 物品价值
     *  protectPrice  | string | 必填  | 保价
     *  packageId     | string | 必填  | 包装id
     *
     * senderInfo
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  name          | string | 必填  | 姓名
     *  phone         | string | 必填  | 联系方式
     *  provId        | int    | 必填  | 省份id
     *  provName      | string | 必填  | 省份
     *  cityId        | int    | 必填  | 城市id
     *  cityName      | string | 必填  | 城市
     *  countyId      | int    | 必填  | 县(区)id
     *  countyName    | string | 必填  | 县(区)
     *  streetId      | int    | 选填  | 街道id
     *  streetName    | string | 选填  | 街道
     *  address       | string | 必填  | 详细地址
     *
     * @return
     *  name    | type | description
     * ---------|------|-------------
     *  orderId | int  | 订单编号
     *
     *
     */
    public function addOrder()
    {
        //寄件人地址
        $sender_info = json_decode(str_replace('\'', "\"", $this->_getContentParams('senderInfo')), true);
        $send_bool_res = UserLogicOrder::getInstance()->checkAreaInfo($sender_info);
        _toCompare($send_bool_res, '==', false, 14010);
        $data['sender_info'] = $send_bool_res;

        //收件人地址
        $recipient_info = json_decode(str_replace('\'', "\"", $this->_getContentParams('recipientInfo')), true);
        $rec_bool_res = UserLogicOrder::getInstance()->checkAreaInfo($recipient_info);
        _toCompare($rec_bool_res, '==', false, 14009);
        $data['recipient_info'] = $rec_bool_res;

        //期望上门类型
        $door_type = $this->_getContentParams('doorType');
        _toCompare(in_array($door_type, ['rightNow', 'today', 'tomorrow', 'afterTomorrow']), '==', false, 14007);

        //期望上门时间
        $door_time = $this->_getContentParams('doorTime');
        $data['door_time'] = UserLogicOrder::getInstance()->getTime($door_type, $door_time);
        _toCompare($data['door_time'], '==', false, 14008);

        //重量
        $data['item_weight'] = $this->_getContentParams('weight');
        _toValidate('math', $data['item_weight'], 14002);
        //物品类型id
        $data['item_type_id'] = $this->_getContentParams('itemTypeId');
        _toValidate('id', $data['item_type_id'], 14003);

        //物品类型
        $data['item_type'] = ModelItemType::getInstance()->getItemName($this->_getContentParams('itemTypeId'));
        _toCompare(empty($data['item_type']), '==', true, 14003);

        //声明价值
        $data['item_price'] = $this->_getContentParams('itemPrice');
        if ($data['item_price'] > 0) {
            _toValidate('money', $data['item_price'], 14004);
        }

        //保价
        $data['protect_price'] = $this->_getContentParams('protectPrice');
        if ($data['protect_price'] > 0) {
            _toValidate('money', $data['protect_price'], 14005);
        }

        //包装值（'不需要包装', '带文件袋', '带包装盒'）
        $package_id = $this->_getContentParams('packageId');
        $res = ModelPackage::getInstance()->checkPackageId($package_id);
        _toCompare($res, '==', false, 14006);
        $data['package'] = $res;

        $data['first_heavy_fee'] = UserLogicOrder::getInstance()->getFirstHeavyFee(); //首重
        $data['other_heavy_fee'] = UserLogicOrder::getInstance()->getNextHeavyFee($data['item_weight']); //续重
        $data['order_amount'] = (int)$data['protect_price'] + $data['first_heavy_fee'] + $data['other_heavy_fee']; //总费用
        $data['order_state'] = 10; //订单状态
//        $data['express_state'] = 100; //物流状态
        $data['user_id'] = $this->user_id; //用户id
        $data['order_sn'] = 'DD'.UserLogicOrder::getInstance()->StrOrderOne(); //订单编号
//        $data['pickup_code'] = ''; //取件码
        //寄件人经纬度
        $data['send_lng'] = $this->_getContentParams('sendLng');
        _toCompare(empty($data['send_lng']), '==', true, 14015);

        $data['send_lat'] = $this->_getContentParams('sendLat');
        _toCompare(empty($data['send_lat']), '==', true, 14015);

        $data['send_area_id'] = $sender_info['streetId'];
        //收件人经纬度
        $data['received_lng'] = $this->_getContentParams('receivedLng');
        _toCompare(empty($data['received_lng']), '==', true, 14015);

        $data['received_lat'] = $this->_getContentParams('receivedLat');
        _toCompare(empty($data['received_lat']), '==', true, 14015);

        $data['received_area_id'] = $recipient_info['streetId'];

        $addOrderId = ModelUserOrder::getInstance()->toAdd($data);
        $addLog = ModelUserOrderLog::getInstance()->addOrderLog($addOrderId,4,$this->user_id,'用户下单');
        if ($addOrderId && $addLog) {
            _returnData(['orderId' => $addOrderId]);
        }
        _returnError(10010);
    }






    /**
     * 上门时间列表 \n
     * URI : /door.list
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 登录凭证
     *
     * @return
     *  name        |  type  | description
     * -------------|--------|-------------
     *  list        | array  | 列表
     *
     * list
     *  name        |  type  | description
     * -------------|--------|-------------
     *  time        | string | 时间
     *
     */
    public function doorTime()
    {
        $list = ModelDoorTime::getInstance()->toSelect([], 'time', null, null, 'sort asc');
        _returnData(['list' => $list]);
    }



}
